package com.time.hellotime.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.time.hellotime.R;
import com.time.hellotime.app.AppConfig;
import com.time.hellotime.app.MyApplication;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 分享操作类
 * Created by Bing on 2017/4/18.
 * E-mail is tx16bing@163.com
 */

public class ShareUtils {

    private volatile static ShareUtils mInstance;

    private ShareUtils() {
        // 私有化构造函数
    }

    public static ShareUtils getInstance() {
        if (mInstance == null) {
            synchronized (ShareUtils.class) {
                if (mInstance == null) {
                    mInstance = new ShareUtils();
                }
            }
        }
        return mInstance;
    }

    /*
        * 获取网络图片
        * 分享到微信的图片的本地地址
        * */
    public void getSharePicPath(String picUrl, String pathName, final ShareCallback callback) {
        // 最后获取的本地路径名
        final String path = AppConfig.getInstance().APP_PATH_ROOT + File.separator + pathName;
        Request<Bitmap> imageRequest = NoHttp.createImageRequest(picUrl);
        NoHttp.newRequestQueue().add(490, imageRequest, new OnResponseListener<Bitmap>() {
            @Override
            public void onStart(int what) {
                Logger.i("Start");
            }

            @Override
            public void onSucceed(int what, Response<Bitmap> response) {
                Logger.i("Succeed");
                Bitmap bitmap = response.get();
//                Bitmap bitmap = decodeSampledBitmapFromPath(path, 720, 1280);
                OutputStream os = null;
                try {
                    os = new FileOutputStream(path);
                    if (bitmap != null) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 70, os);
                    }
                } catch (Exception e) {

                } finally {
                    if (callback !=null){
                        callback.onSucceed(path);
                    }
                    CloseUtils.close(os);
                }

            }

            @Override
            public void onFailed(int what, Response<Bitmap> response) {
                Logger.i("Failed");
            }

            @Override
            public void onFinish(int what) {
                Logger.i("Finish");
            }
        });
    }

    /*
   * 获取本地图片
   * 分享到微信的图片的本地地址
   * */
    @SuppressWarnings("ResourceType")
    public String getSharePicPath(String pathName) {
        Resources resources = MyApplication.getInstance().getResources();
        OutputStream os = null;
        InputStream is = resources.openRawResource(R.drawable.iv_share_logo);
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        String path = AppConfig.getInstance().APP_PATH_ROOT + File.separator + pathName;
        try {
            os = new FileOutputStream(path);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            }
        } catch (Exception e) {

        } finally {
            CloseUtils.close(os);
        }
        return path;
    }

    /**
     * 根据图片要显示的宽和高，对图片进行压缩，避免OOM
     *
     * @param path
     * @param width  要显示的imageview的宽度
     * @param height 要显示的imageview的高度
     * @return
     */
    private Bitmap decodeSampledBitmapFromPath(String path, int width, int height) {

//      获取图片的宽和高，并不把他加载到内存当中
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = caculateInSampleSize(options, width, height);
//      使用获取到的inSampleSize再次解析图片(此时options里已经含有压缩比 options.inSampleSize，再次解析会得到压缩后的图片，不会oom了 )
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;

    }

    /**
     * 根据需求的宽和高以及图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param reqWidth  要显示的imageview的宽度
     * @param reqHeight 要显示的imageview的高度
     * @return
     * @compressExpand 这个值是为了像预览图片这样的需求，他要比所要显示的imageview高宽要大一点，放大才能清晰
     */
    private int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width >= reqWidth || height >= reqHeight) {

            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(width * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);

        }

        return inSampleSize;
    }

    public interface ShareCallback {

        void onSucceed(String path);

    }

}
